package com.ywdnf.gomoku.web.control;

import com.ywdnf.gomoku.model.chess.Game;
import com.ywdnf.gomoku.model.chess.GameState;
import com.ywdnf.gomoku.model.chess.SimpleGame;
import com.ywdnf.gomoku.util.CommonUtil;
import com.ywdnf.gomoku.util.Const;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * page controller
 *
 * @author lss
 * @date 2019-06-25, Tue
 */
@Controller
public class PageController {


  @GetMapping({"/", "index", ""})
  public String index(Model model) {
    ConcurrentHashMap<String, Game> games = GomokuController.getAll();
    List<SimpleGame> sgs = new ArrayList<>();
    games.forEach((k, v) -> {
      if (v.getState() == GameState.WAITING_FOR_START && !v.isHide()) {
        String gbId = CommonUtil.getBriefGameId(k);
        sgs.add(new SimpleGame(gbId, v.getName(), v.getCreator().getNick(),
            CommonUtil.convertTimeToString(v.getGmtCreated()), CommonUtil.getReturnALinkToGmk(gbId)));
      }
    });
    // sgs.sort((o1,o2)-> {
    //   return o1.getGmtCreated() - o2.getGmtCreated()
    // });
    model.addAttribute("SGS", sgs);
    return "index";
  }


  @GetMapping("/gomoku/{gameId}")
  public String gomoku(
      @RequestParam(value = Const.PARAM_GAME_ID_IN_URL) String gameId,
      @RequestParam(value = Const.PARAM_USER_ID_IN_URL) String userId,
      @PathVariable(Const.PARAM_GAME_ID_IN_URL) String gameId2, Model model,
      HttpServletRequest request) {
    if (StringUtils.isEmpty(gameId)) {
      return "redirect:/";
    }

    Game game = GomokuController.getGame(gameId);
    if (game == null) {
      return "redirect:/";
    }
    if (!CommonUtil.getBriefGameId(gameId).equals(gameId2)) {
      return "redirect:/";
    }

    model.addAttribute("GAME_NAME", game.getName());
    model.addAttribute("GAME_BRIEF_ID", gameId2);
    model.addAttribute("ME", CommonUtil.getSelfPlayer(userId, game));
    return "gomoku";
  }


}
